#ifndef SCIENTIFIC_CALCULATION_H
#define SCIENTIFIC_CALCULATION_H

#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <unordered_map>
#include <atomic>


struct DataResult {
    double original_data;
    bool result; // true if the processed data is divisible by 2, false otherwise
};

template<typename T>
class ThreadSafeQueue {
    std::queue<T> queue;
    mutable std::mutex mutex;
    std::condition_variable cond;

public:
    void push(T value) {
        std::lock_guard<std::mutex> lock(mutex);
        queue.push(std::move(value));
        cond.notify_one();
    }

    bool try_pop(T& value) {
        std::lock_guard<std::mutex> lock(mutex);
        if(queue.empty()) return false;
        value = std::move(queue.front());
        queue.pop();
        return true;
    }

    void wait_and_pop(T& value) {
        std::unique_lock<std::mutex> lock(mutex);
        cond.wait(lock, [this]{ return !queue.empty(); });
        value = std::move(queue.front());
        queue.pop();
    }

    // 添加此方法以允许外部通知所有等待的线程
    void notify_all() {
        cond.notify_all();
    }
};

class ScientificCalculation {
    ThreadSafeQueue<DataResult> dataprocess_queue;
    ThreadSafeQueue<DataResult> calculate_queue;
    ThreadSafeQueue<DataResult> final_results;
    std::vector<std::thread> threads;
    std::atomic<bool> done{false};
    int task_counter = 0;
    std::unordered_map<double, bool> results_map;
    std::mutex results_mutex;
    std::condition_variable cv;
    
    void wait_for_completion();

    void dataprocess();
    void calculate();
    void results_analysis();

public:
    void init();
    std::unordered_map<double, bool> inference(const std::vector<double>& inputs); // 修改为返回结果
    ScientificCalculation();
    ~ScientificCalculation();
};

#endif //SCIENTIFIC_CALCULATION_H
